package uns.fit.gis.mapdrawer;

import henson.midp.Float;
import uns.fit.gis.MathFP;
import uns.fit.gis.mapobj.Point;

public class MapRotation {
	private final static int SIN_10_1000 = 173;
	private final static int COS_10_1000 = 985;
	private static int[] counterclockwiseMatrix = {	COS_10_1000, -SIN_10_1000,
												SIN_10_1000, COS_10_1000};
	private static int[] clockwiseMatrix = {	COS_10_1000, SIN_10_1000,
													-SIN_10_1000, COS_10_1000};
	
	public static Point rotateClockwise(int x, int y) {
		int newX = clockwiseMatrix[0] * x + clockwiseMatrix[1] * y;
		int newY = clockwiseMatrix[2] * x + clockwiseMatrix[3] * y;
		return new Point(newX / 1000, newY / 1000);
	}
	
	public static Point rotateCounterclockwise(int x, int y) {
		int newX = counterclockwiseMatrix[0] * x + counterclockwiseMatrix[1] * y;
		int newY = counterclockwiseMatrix[2] * x + counterclockwiseMatrix[3] * y;
		return new Point(newX / 1000, newY / 1000);
	}
	
	public static void setCos1000(int cos1000) {
		clockwiseMatrix[0] = clockwiseMatrix[3] = counterclockwiseMatrix[0] = counterclockwiseMatrix[3] = cos1000;
		//String str = Double.toString(cos1000 * 1.0 / 1000);
		//System.out.println(str);
		//long x = MathFP.toFP(str);
		Float f = new Float(cos1000);
		f = f.Div(new Float(1000));
		System.out.println("COS = " + f.toString());
		f = Float.acos(f);
		//f = Float.toDegrees(f);
		System.out.println("RADIAN = " + f.toString());
		if(f.Great(Float.PIdiv2))
			clockwiseMatrix[1] = counterclockwiseMatrix[2] = (int)Math.sqrt(1000000 - cos1000 * cos1000);
		else
			clockwiseMatrix[1] = counterclockwiseMatrix[2] = -(int)Math.sqrt(1000000 - cos1000 * cos1000);
		clockwiseMatrix[2] = counterclockwiseMatrix[1] = -counterclockwiseMatrix[2];
	}
	
	/*
	 * Bi loi khi chay Driving Assist
	 */
	public static Point rotate(Point point, Point center, int angle) {
		/*
		 * Fireproof code
		 */
		if(center == null)
			return point;
		/*
		 * End of fireproof code
		 */
		double a = Math.toRadians(angle);
		double newX = (point.getX() - center.getX()) * Math.cos(a) - (point.getY() - center.getY()) * Math.sin(a) + center.getX();
		double newY = (point.getY() - center.getY()) * Math.cos(a) + (point.getX() - center.getX()) * Math.sin(a) + center.getY();
		return new Point((int)newX, (int)newY);
	}
	
	/*
	 * Rotate around center of screen
	 */
	public static Point rotate(Point point, int angle) {
		if(angle == 0)
			return point;
		double a = Math.toRadians(angle);
		double newX = (point.getX() - MapCanvas.screenWidthDiv2) * Math.cos(a) - (point.getY() - MapCanvas.screenHeightDiv2) * Math.sin(a) + MapCanvas.screenWidthDiv2;
		double newY = (point.getY() - MapCanvas.screenHeightDiv2) * Math.cos(a) + (point.getX() - MapCanvas.screenWidthDiv2) * Math.sin(a) + MapCanvas.screenHeightDiv2;
		return new Point((int)newX, (int)newY);
	}
}
